package com.example.calculator;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Calculator extends Activity implements OnTouchListener {

	private double tempNumber;
	private TextView calcDisplay;
	private TextView actions;
	private ImageView actionsAnimation;
	private Animation anim;
	private int calcDisplayLenght;
	private int calcDisplayTextSize;
	private boolean isReset;
	private boolean isFirstNumber;
	private String sign;
	private int actionsCounter;
	private int actionIndex;
	private int prevActionIndex;
	private boolean canTapNumber;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.calculator_layout);

		anim = AnimationUtils.loadAnimation(Calculator.this, R.anim.animation);
		calcDisplayLenght = 3;
		calcDisplayTextSize = 110;
		tempNumber = 0;
		sign = null;
		isReset = true;
		canTapNumber = true;
		isFirstNumber = true;
		actionIndex = 0;
		prevActionIndex = 0;
		actionsCounter = 0;
		setViews();
		setButtons();
		

		findViewById(R.id.rootLayout).setOnTouchListener(
				new OnSwipeTouchListener() {

					public void onSwipeTop() {
						reset();
						runAnimation(5);
					}

					public void onSwipeRight() {

						if (actionIndex == 1 && actionsCounter != 0) {
							actions(3);
						} else {
							actions(1);
						}
					}

					public void onSwipeLeft() {
						if (actionIndex == 2 && actionsCounter != 0) {
							actions(4);
						} else {
							actions(2);
						}
					}

					public void onSwipeBottom() {
						equal();
					}
				});

	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			Intent intent = new Intent(this, CustomMenu.class);

			startActivityForResult(intent, 0);
			return true;
		}

		return super.onKeyUp(keyCode, event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != RESULT_OK) {
			return;
		}
		if (requestCode == 0) {

			int result = data.getIntExtra("Action", 13);
			switch (result) {
			case 6:
				sqrtRoot();
				break;
			case 7:
				plusMinus();
				break;
			default:
				actions(result);
				break;
			}
		}
	}

	private void setViews() {
		actionsAnimation = (ImageView) findViewById(R.id.actionsAnimation);
		calcDisplay = (TextView) findViewById(R.id.display);
		actions = (TextView) findViewById(R.id.action);
		calcDisplay
				.setTextSize(TypedValue.COMPLEX_UNIT_SP, calcDisplayTextSize);
		actions.setTextSize(TypedValue.COMPLEX_UNIT_SP, 60);
	}

	private void setButtons() {
		findViewById(R.id.button0).setOnTouchListener(Calculator.this);
		findViewById(R.id.button1).setOnTouchListener(Calculator.this);
		findViewById(R.id.button2).setOnTouchListener(Calculator.this);
		findViewById(R.id.button3).setOnTouchListener(Calculator.this);
		findViewById(R.id.button4).setOnTouchListener(Calculator.this);
		findViewById(R.id.button5).setOnTouchListener(Calculator.this);
		findViewById(R.id.button6).setOnTouchListener(Calculator.this);
		findViewById(R.id.button7).setOnTouchListener(Calculator.this);
		findViewById(R.id.button8).setOnTouchListener(Calculator.this);
		findViewById(R.id.button9).setOnTouchListener(Calculator.this);
		findViewById(R.id.buttonPoint).setOnTouchListener(Calculator.this);
		findViewById(R.id.info_icon).setOnTouchListener(Calculator.this);
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		int eventAction = event.getAction();
		if (eventAction == MotionEvent.ACTION_DOWN) {
			if (v.getId() != R.id.info_icon) {
				findViewById(v.getId()).setBackgroundResource(
						R.drawable.btn_pressed);
			}

			switch (v.getId()) {
			case R.id.button0:
				numbers("0");
				break;
			case R.id.button1:
				numbers("1");
				break;
			case R.id.button2:
				numbers("2");
				break;
			case R.id.button3:
				numbers("3");
				break;
			case R.id.button4:
				numbers("4");
				break;
			case R.id.button5:
				numbers("5");
				break;
			case R.id.button6:
				numbers("6");
				break;
			case R.id.button7:
				numbers("7");
				break;
			case R.id.button8:
				numbers("8");
				break;
			case R.id.button9:
				numbers("9");
				break;
			case R.id.buttonPoint:
				numbers(".");
				break;
			case R.id.info_icon:
				Intent infoIntent = new Intent(this, Info.class);
				startActivity(infoIntent);
				break;
			default:
				break;
			}
		} else if (eventAction == MotionEvent.ACTION_UP) {
			if (v.getId() != R.id.info_icon) {
				findViewById(v.getId()).setBackgroundResource(R.drawable.btn);
			}
		}
		return true;
	}

	private void numbers(String number) {
		if (canTapNumber == true) {
			if (number.charAt(0) == '.' && isReset == true) {
				return;
			} else {

				if (number == "."
						&& String.valueOf(calcDisplay.getText()).indexOf(".") != -1) {
					return;
				}

				isReset = false;

				if (isFirstNumber == false && actionsCounter != 0) {

					calcDisplay.setText("");
				}

				actionsCounter = 0;

				if (calcDisplay.length() <= calcDisplayLenght) {
					calcDisplay.append(number);
				} else {
					if (calcDisplay.length() < 12) {
						calcDisplayLenght += 5;
						calcDisplayTextSize -= 20;
						calcDisplay.setTextSize(TypedValue.COMPLEX_UNIT_SP,
								calcDisplayTextSize);
						calcDisplay.append(number);
					}
				}
			}
		}

	}

	private void actions(int index) {

		if (isReset == true) {
			return;
		} else {

			runAnimation(index);

			actionIndex = index;

			if (!TextUtils.isEmpty(calcDisplay.getText().toString())) {

				if (isFirstNumber == false && actionsCounter == 0) {
					calcDisplay.setText(result(prevActionIndex));
					Toast.makeText(
							this,
							"Временен резултат: "
									+ calcDisplay.getText().toString(),
							Toast.LENGTH_SHORT).show();
				}

				String tempString = calcDisplay.getText().toString();
				tempString.trim();
				tempNumber = Double.parseDouble(tempString);
			}

			actions.setText(sign);
			calcDisplay.setText("");

			prevActionIndex = index;

			if (actionsCounter == 0) {
				isFirstNumber = false;
			}
			actionsCounter = 1;
			canTapNumber = true;

		}
	}

	private String result(int index) {

		String result = null;

		double firstNumber = tempNumber;
		double secondNumber = Double.parseDouble(calcDisplay.getText()
				.toString().trim());

		switch (index) {
		case 1:
			result = String.valueOf(Actions.getAddition(firstNumber,
					secondNumber));
			break;
		case 2:
			result = String.valueOf(Actions.getSubtraction(firstNumber,
					secondNumber));
			break;
		case 3:
			result = String.valueOf(Actions.getMultiplication(firstNumber,
					secondNumber));
			break;
		case 4:
			try {
				result = String.valueOf(Actions.getDivision(firstNumber,
						secondNumber));
			} catch (ArithmeticException ae) {
				result = ae.getMessage();
			}
			break;
		case 5:

			break;
		case 6:
			try {
				result = String.valueOf(Actions.getSquareRoot(secondNumber));
			} catch (ArithmeticException ae) {
				result = ae.getMessage();
			}
			break;
		default:
			result = "0";
			break;
		}

		tempNumber = 0;

		if (isInteger(result)) {
			tempNumber = Double.parseDouble(result);

		} else {
			reset();
			calcDisplay.setTextSize(TypedValue.COMPLEX_UNIT_SP, 30);

		}
		
		return result;

	}

	private void equal() {
		if (isReset == true || actionsCounter != 0) {

			actions.setText("=");
			runAnimation(8);
			calcDisplay.setText(String.valueOf(tempNumber));
			return;

		} else {
			calcDisplay.setText(result(actionIndex));
			actions.setText("=");
		}
		isFirstNumber = true;
		canTapNumber = false;

		runAnimation(8);

	}

	private void reset() {
		calcDisplay.setText(null);
		actions.setText("");
		tempNumber = 0;
		actionIndex = 0;
		isReset = true;
		isFirstNumber = true;
		canTapNumber = true;
		calcDisplayTextSize = 110;
		calcDisplay
				.setTextSize(TypedValue.COMPLEX_UNIT_SP, calcDisplayTextSize);
		calcDisplayLenght = 3;
	}

	private void plusMinus() {
		String tempValue = calcDisplay.getText().toString();
		tempValue.trim();

		if (isInteger(tempValue) && tempValue != "") {
			if (tempValue.charAt(0) == '-') {
				tempValue = tempValue.substring(1);
				calcDisplay.setText(tempValue);
			} else {
				tempValue = "-" + tempValue;
				calcDisplay.setText(tempValue);
			}

			runAnimation(7);
		}
	}

	private void sqrtRoot() {
		runAnimation(6);
		actions.setText(sign);
		actionIndex = 6;
	}

	public boolean isInteger(String input) {
		try {
			Double.parseDouble(input);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	private void runAnimation(int index) {

		switch (index) {
		case 1:
			actionsAnimation.setImageResource(R.drawable.actions_addition);
			sign = "+";
			break;
		case 2:
			actionsAnimation.setImageResource(R.drawable.actions_subtraction);
			sign = "-";
			break;
		case 3:
			actionsAnimation
					.setImageResource(R.drawable.actions_multiplication);
			sign = "×";
			break;
		case 4:
			actionsAnimation.setImageResource(R.drawable.actions_division);
			sign = "÷";
			break;
		case 5:
			actionsAnimation.setImageResource(R.drawable.actions_reset);
			break;
		case 6:
			actionsAnimation.setImageResource(R.drawable.actions_root);
			sign = "√";
			break;
		case 7:
			actionsAnimation.setImageResource(R.drawable.actions_plus_minus);
			break;
		case 8:
			actionsAnimation.setImageResource(R.drawable.actions_equal);
			break;
		default:
			break;
		}

		actionsAnimation.startAnimation(anim);

	}

}
